/*


Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package controllers

import (
	"context"
	"encoding/base64"
	"fmt"
	"github.com/go-logr/logr"
	ckev1alpha1 "iop.inspur.com/api/v1alpha1"
	"iop.inspur.com/constants"
	batchv1 "k8s.io/api/batch/v1"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"regexp"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"strconv"
	"strings"
)

// CkePatchReconciler reconciles a CkePatch object
type CkePatchReconciler struct {
	client.Client
	Log    logr.Logger
	Scheme *runtime.Scheme
}

type PatchInformation struct {
	Name        string
	ImageName   string
	CurrVersion string // 当前升级的版本
	ToVersion   string // 要升级的版本
	Status      string
}

// +kubebuilder:rbac:groups=cke.inspur.com,resources=ckepatches,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=cke.inspur.com,resources=ckepatches/status,verbs=get;update;patch
func (r *CkePatchReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {
	_ = context.Background()
	_ = r.Log.WithValues("CkePatch", req.NamespacedName)

	return ctrl.Result{}, nil
}

func (r *CkePatchReconciler) SetupWithManager(mgr ctrl.Manager) error {
	return ctrl.NewControllerManagedBy(mgr).
		For(&ckev1alpha1.CkePatch{}).
		Complete(r)
}

func newPatchJob(ckecluster *ckev1alpha1.CkeCluster, nodes *ckev1alpha1.CkeNodeList, patch *PatchInformation) *batchv1.Job {
	var Para, Back, Com, Model = int32(1), int32(3), int32(1), int32(0600)
	var fork = strconv.Itoa(constants.ForkThreads)
	if ckecluster == nil || nodes == nil || patch == nil {
		return nil
	}
	var CkeDeployImageName = ImageGetFromConfigWithTag(&ckecluster.Spec, patch.ToVersion)
	var CkePatchImageName = PatchImageGetFromConfig(&ckecluster.Spec, patch)
	var CkeConfigContent = Base64Context(ckecluster, &nodes.Items)

	return &batchv1.Job{
		ObjectMeta: metav1.ObjectMeta{
			Name:      fmt.Sprintf("%s-%s", PatchJobAppLabel, RandomUID()),
			Namespace: ckecluster.Namespace,
			OwnerReferences: []metav1.OwnerReference{
				*metav1.NewControllerRef(ckecluster, schema.GroupVersionKind{Group: ckev1alpha1.GroupVersion.Group, Version: ckev1alpha1.GroupVersion.Version, Kind: "CkeCluster"}),
			},
			Labels: map[string]string{
				"app":         PatchJobAppLabel,
				"version":     patch.CurrVersion,
				"patchSerial": fmt.Sprintf("b%se", StrNoLongThan(base64.RawURLEncoding.EncodeToString([]byte(patch.Name)), constants.AnnotationLengthLimit-2)),
			},
		},
		Spec: batchv1.JobSpec{
			Parallelism:  &Para,
			BackoffLimit: &Back,
			Completions:  &Com,
			Template: corev1.PodTemplateSpec{
				ObjectMeta: metav1.ObjectMeta{
					Name: PatchJobAppLabel,
				},
				Spec: corev1.PodSpec{
					HostNetwork: true,
					NodeSelector: map[string]string{
						"beta.kubernetes.io/os":          "linux",
						"node-role.kubernetes.io/master": "true",
					},
					Tolerations: []corev1.Toleration{
						{
							Key:      "CriticalAddonsOnly",
							Operator: "Exists",
						},
						{
							Operator: "Exists",
							Effect:   "NoExecute",
						},
						{
							Operator: "Exists",
							Effect:   "NoSchedule",
						},
					},
					Containers: []corev1.Container{
						// cke-deploy images, exec ansible command
						{
							Name:            PatchJobAppLabel,
							Image:           CkeDeployImageName,
							ImagePullPolicy: corev1.PullIfNotPresent,
							Command: []string{
								"/bin/playbook",
								"--execyml",
								fmt.Sprintf("%s.%s", patch.Name, constants.PatchFileTag),
								"--before",
								fmt.Sprintf("cp %s %s", fmt.Sprintf("%s/%s.%s", "/opt/kubernetes-deploy/roles/iop-patch", patch.Name, constants.PatchFileTag), constants.KubeDeployDir),
								"--wait",
								"2",
								"--config",
								CkeConfigContent,
								"--fork",
								fork,
								"--logpath",
								constants.LogsInpodDir,
								"--logname",
								patch.Name,
							},
							Env: []corev1.EnvVar{
								{
									Name:  "ANSIBLE_HOST_KEY_CHECKING",
									Value: "Flase",
								},
								{
									Name:  "ANSIBLE_GATHERING",
									Value: "explicit",
								},
							},
							VolumeMounts: []corev1.VolumeMount{
								{
									MountPath: "/root/.ssh/",
									Name:      "cke-certs",
								},
								{
									MountPath: "/opt/kubernetes-deploy/roles/iop-patch/",
									Name:      "share-volume",
								},
								{
									MountPath: constants.LogsInpodDir,
									Name:      "ckelogs",
								},
							},
						},
					},
					InitContainers: []corev1.Container{
						// cke-patch images, copy patchs to share-volume
						{
							Name:            "cke-patchs-container",
							Image:           CkePatchImageName,
							ImagePullPolicy: corev1.PullIfNotPresent,
							Command: []string{
								"sh",
								"-c",
								fmt.Sprintf("cp -rf %s %s %s", fmt.Sprintf("%s/%s*", "/opt/patch", patch.Name), "/opt/patch/iop-patch/*", "/opt/share-volume/"),
							},
							VolumeMounts: []corev1.VolumeMount{
								{
									MountPath: "/root/.ssh/",
									Name:      "cke-certs",
								},
								{
									MountPath: "/opt/share-volume/",
									Name:      "share-volume",
								},
							},
						},
					},
					RestartPolicy: corev1.RestartPolicyOnFailure,
					Volumes: []corev1.Volume{
						{
							Name: "cke-certs",
							VolumeSource: corev1.VolumeSource{
								Secret: &corev1.SecretVolumeSource{
									DefaultMode: &Model,
									SecretName:  "cke-certs",
								},
							},
						},
						{
							Name: "share-volume",
							VolumeSource: corev1.VolumeSource{
								EmptyDir: &corev1.EmptyDirVolumeSource{},
							},
						},
						{
							Name: "ckelogs",
							VolumeSource: corev1.VolumeSource{
								HostPath: &corev1.HostPathVolumeSource{
									Path: constants.PatchLogDir,
									Type: &constants.MountPathDirType,
								},
							},
						},
					},
				},
			},
		},
	}
}

func PatchImageGetFromConfig(config *ckev1alpha1.CkeClusterSpec, patch *PatchInformation) string {
	var name = string(regexp.MustCompile("-amd64:|-arm64:|-mips64el:|-mips64:|-mips64le:").ReplaceAll([]byte(patch.ImageName), []byte(":")))

	if strings.Count(name, ":") != 1 {
		return constants.EmptyString
	}

	return GetImage(config.Registry.Domain, config.Registry.Port, strings.Split(name, ":")[0], strings.Split(name, ":")[1], config.ClusterParameters.ImageManifestEnabled)
}
